package com.hlju.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hlju.reggie.bean.Cart;
import com.hlju.reggie.common.BaseContext;
import com.hlju.reggie.common.R;
import com.hlju.reggie.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/shoppingCart")
public class CartController {

    @Autowired
    private CartService cartService;

    //添加购物车
    @PostMapping("/add")
    public R<Cart> add(@RequestBody Cart cart){
        return R.sucess(cartService.addCart(cart));
    }

    //查询购物车
    @GetMapping("/list")
    public R<List> list(){
        QueryWrapper<Cart> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", BaseContext.getCurrentId() );
        wrapper.orderByDesc("create_time");
        return R.sucess(cartService.list(wrapper));
    }

    //清空购物车
    @DeleteMapping("/clean")
    public R<String> clean(){
        QueryWrapper<Cart> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", BaseContext.getCurrentId() );
        return cartService.remove(wrapper)?R.sucess("删除成功"):R.error("删除失败");
    }

    //减少购物车数量
    @PostMapping("/sub")
    public R<Cart> sub(@RequestBody Cart cart){
        //创建条件构造器
        QueryWrapper<Cart> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",BaseContext.getCurrentId());
        //获取菜品id
        Long dishId = cart.getDishId();
        //判断当前是菜品还是套餐
        if(dishId != null){
            wrapper.eq("dish_id",dishId);
        }else{
            wrapper.eq("setmeal_id",cart.getSetmealId());
        }
        //查询出当前购物车数据
        Cart carData = cartService.getOne(wrapper);
        //设置数量
        carData.setNumber(carData.getNumber() - 1);
        //执行更新
        cartService.updateById(carData);
        //判断更新后的数量
        if(carData.getNumber() <= 0){
            //删除当前数据
            cartService.remove(wrapper);
        }
        //返回当前操作后的对象
        return R.sucess(carData);
    }
}
